package cn.gson.boot.model.service;

import cn.gson.boot.model.dao.RoleDao;
import cn.gson.boot.model.dao.YuanGongJueSeDao;
import cn.gson.boot.model.mapper.EmpRoleMapper;
import cn.gson.boot.model.pojos.Role;
import cn.gson.boot.model.pojos.YuangongJuese;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class EmpRoleService {
    @Autowired
    EmpRoleMapper empRoleMapper;

    @Autowired
    YuanGongJueSeDao yuanGongJueSeDao;

    @Autowired
    RoleDao roleDao;

    //根据部门id查看角色
    @Transactional(transactionManager = "transactionManager")
    public List<Role> roleAlls(Integer deptId){
        return empRoleMapper.roleAlls(deptId);
    }

    //确定选择角色
    public void saveRole(Integer empId,String jsList){
        System.err.println("SPgnList:"+jsList);
        System.err.println("empId:"+empId);
        if(jsList.length()>0){
            String[] sp = jsList.split(",");
            //先删除此角色的所有功能
            yuanGongJueSeDao.deleteEmpJueSe(empId);
            //再新增
            YuangongJuese rg = null;
            for (int i=0;i<sp.length;i++){
                System.err.println("sp:"+sp[i]);
                rg = new YuangongJuese(empId,Integer.parseInt(sp[i]));
                yuanGongJueSeDao.save(rg);
            }
        }else{
            yuanGongJueSeDao.deleteEmpJueSe(empId);
        }
    }

    public List<Role> xvniRoleSBSB(String jsList) {
        String[] sp = jsList.split(",");
        List<Role> rr = new ArrayList<>();
        //根据角色id查找到角色对象
        for (int i=0;i<sp.length;i++){
            rr.add(empRoleMapper.xvniRoleSBSB(Integer.parseInt(sp[i])));
        }
        return rr;
    }


    //查看所有的角色
    public List<Role> selectAllRoles(){
        return empRoleMapper.selectAllRoles();
    }

    //根据部门id查看角色
    public List<Integer> roleAllsBydeptId(Integer deptId){
        return empRoleMapper.roleAllsBydeptId(deptId);
    }

    //确定对部门下的角色管理
    public void baocunBMGLjuese(Integer deptId,String jsList2) {
        String[] sp = jsList2.split(",");

        //先把此部门的所有角色移除掉，把dept_id设为null
        List<Integer> ss = empRoleMapper.roleAllsBydeptId(deptId);
        for (int i=0;i<ss.size();i++){
            roleDao.updateJueseDeBuMen(null,ss.get(i));
        }


        for (int i=0;i<sp.length;i++){
            roleDao.updateJueseDeBuMen(deptId,Integer.parseInt(sp[i]));
        }
    }

    //根据员工id查找角色-->empId
    public List<Integer> roleAllsByempId(Integer empId){
        return empRoleMapper.roleAllsByempId(empId);
    }
}
